import React, { useState, useEffect } from 'react';
import { EditorState, ContentState, CompositeDecorator } from 'draft-js';
import { Editor } from 'react-draft-wysiwyg';
import 'react-draft-wysiwyg/dist/react-draft-wysiwyg.css';

const findWithRegex = (regex, contentBlock, callback) => {
  const text = contentBlock.getText();
  let matchArr;
  let start;
  // 在while循环前进行第一次赋值，并使用另一个变量进行条件检查
  let isMatchNotNull = true; // 新添加的变量，用于检查是否匹配为空
  matchArr = regex.exec(text); // 在循环前进行第一次执行和赋值

  while (isMatchNotNull) {
    if (matchArr === null) {
      isMatchNotNull = false;
      break; // 如果匹配为空，退出循环
    }
    console.log('Matched text:', matchArr[0]);
    start = matchArr.index;
    callback(start, start + matchArr[0].length);

    matchArr = regex.exec(text); // 在循环末尾重新执行和赋值
  }
};

const compositeDecorator = new CompositeDecorator([
  {
    strategy: (contentBlock, callback, contentState) => {
      console.log('Strategy called');
      findWithRegex(/\[\[test\]\]/g, contentBlock, callback);
    },
    component: (props) => {
      console.log('Component rendering with children:', props.children);
      return (
        <span style={{ backgroundColor: '#e0e0e0', padding: '5px', borderRadius: '5px' }} {...props}>
          {props.children}
        </span>
      );
    }
  }
]);

const SimpleDraftField = () => {
  const [editorState, setEditorState] = useState(null);

  useEffect(() => {
    const initialContent = 'Simple editor with [[test]].';
    setEditorState(EditorState.createWithContent(ContentState.createFromText(initialContent), compositeDecorator));
  }, []);

  const onEditorStateChange = (editor) => {
    setEditorState(editor);
  };

  if (!editorState) return null; // 如果editorState还没有初始化，返回null

  return <Editor editorState={editorState} onEditorStateChange={onEditorStateChange} />;
};

export default SimpleDraftField;
